package cn.learn.filter;


import cn.learn.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * token的授权校验过滤器，用来拦截oauth2不起作用
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2020年07月19日18:38
 */
//@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    private final static Logger logger = LoggerFactory.getLogger(TokenAuthenticationFilter.class);


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String              token = httpServletRequest.getHeader("Authorization");
        Map<String, Object> map   = null;
        //从token中获取用户string信息
        try {
            String user = URLDecoder.decode(token, "UTF-8");
            map = JsonUtil.string2Map(user);
            String[] authorities = (String[]) map.get("authorities");
            //将用户信息和权限填充到用户身份token对象中
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(token, null, AuthorityUtils.createAuthorityList(authorities));
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
            //将authenticationToken 填充到安全上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } catch (UnsupportedEncodingException e) {
            logger.warn("解析请求头字符集解码出错{}", e.getMessage());
        }

        if (map != null) {

        } else {

            logger.info("请求中没有获取到该用户的账户：");
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}
